<template>
  <t-modal
      :title="title"
      :width="1000"
      :visible="visible"
      :confirmLoading="loading"
      @ok="
			() => {
				$emit('ok');
			}
		"
      @cancel="
			() => {
				$emit('cancel');
			}
		"
      :fullscreen="true"
      :switchFullscreen="true"
  >
    <a-spin :spinning="loading">
      <a-form :form="form">
        <a-row :gutter="16">
          <a-form-item class="hiddenItem">
            <!-- uuid隐藏 -->
            <a-input v-decorator="['uuid']" disabled type="hidden"/>
          </a-form-item>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="表名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['tableName',{ rules: [{ required: true, message: '必填' }]}]"
                       placeholder="请输入表名"
              />
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="表注释" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['tableComment']"
                       placeholder="请输入表注释"
                       :auto-size="{ minRows: 3, maxRows: 5 }"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">字段信息</a-divider>
        <div class="margin-xs">
          <a-button type="primary" icon="plus" @click="handleAdd">新增字段</a-button>
        </div>
        <a-table :columns="columns" :data-source="data" :bordered="false" size="small" rowKey="index" :pagination="false">
          <template
              v-for="col in ['fieldName', 'fieldComment','defaultValue','fieldDecimalPoint']"
              :slot="col"
              slot-scope="text, record, index"
          >
            <div :key="col">
              <a-form-item>
                <a-input
                    v-decorator="[
                      col + record.id,
                      { initialValue: text, rules: getOptionRules(col) },
                      ]"
                    allowClear
                    @change="e => handleChange(e.target.value, index, col)"
                />
              </a-form-item>
            </div>
          </template>
          <template
              :slot="'fieldType'"
              slot-scope="text, record, index"
          >
            <a-form-item>
              <div>
                <a-select
                          style="width: 100%"
                          @change="val => handleChange(val, index, 'fieldType')"
                          v-decorator="[
                          'fieldType' + record.id,
                          { initialValue: text, rules: getOptionRules('fieldType') },
                          ]"
                >
                  <a-select-option value="VARCHAR">
                    VARCHAR
                  </a-select-option>
                  <a-select-option value="INT">
                    INT
                  </a-select-option>
                </a-select>
              </div>
            </a-form-item>
          </template>
          <template
              :slot="'fieldLength'"
              slot-scope="text, record, index"
          >
            <a-form-item>
              <div>
                <a-input-number
                                :min="0"
                                :max="10"
                                @change="val => handleChange(val, index, 'fieldLength')"
                                v-decorator="[
                                'fieldLength' + record.id,
                                { initialValue: text, rules: getOptionRules('fieldfieldLength') },
                                ]"
                />
              </div>
            </a-form-item>
          </template>
          <template
              :slot="'fieldPrimaryKey'"
              slot-scope="text, record, index"
          >
            <div>
              <a-checkbox
                  @change="e => handleChange(e.target.checked, index, 'fieldPrimaryKey')"
              >
              </a-checkbox>
            </div>
          </template>
          <template
              :slot="'fieldAllowNull'"
              slot-scope="text, record, index"
          >
            <div>
              <a-checkbox
                  @change="e => handleChange(e.target.checked, index, 'fieldAllowNull')"
              >
              </a-checkbox>
            </div>
          </template>

          <template slot="operation" slot-scope="text, record, index">
            <div class="editable-row-operations">
            <span>
              <a-popconfirm title="确定删除吗？" @confirm="() => handleDel(index)">
                <a class="action-delete">删除</a>
              </a-popconfirm>
            </span>
            </div>
          </template>
        </a-table>
      </a-form>
    </a-spin>
  </t-modal>
</template>

<script>
  import pick from 'lodash.pick';
  import TDictSelectTag from '@/components/TopVUI/dict/TDictSelectTag';
  import ARow from "ant-design-vue/es/grid/Row";


  // 表单字段
  const fields = ['tableName', 'tableComment'];
  //表头
  const columns = [
    {
      title: '字段名称',
      dataIndex: 'fieldName',
      scopedSlots: {customRender: 'fieldName'},
    },
    {
      title: '字段类型',
      dataIndex: 'fieldType',
      width: '15%',
      scopedSlots: {customRender: 'fieldType'},
    },
    {
      title: '长度',
      dataIndex: 'fieldLength',
      scopedSlots: {customRender: 'fieldLength'},
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      scopedSlots: {customRender: 'defaultValue'},
    },
    {
      title: '小数点',
      dataIndex: 'fieldDecimalPoint',
      scopedSlots: {customRender: 'fieldDecimalPoint'},
    },
    {
      title: '注释',
      dataIndex: 'fieldComment',
      scopedSlots: {customRender: 'fieldComment'},
    },
    {
      title: '允许空值',
      dataIndex: 'fieldAllowNull',
      scopedSlots: {customRender: 'fieldAllowNull'},
    },
    {
      title: '主键',
      dataIndex: 'fieldPrimaryKey',
      scopedSlots: {customRender: 'fieldPrimaryKey'},
    },
    {
      title: '操作',
      dataIndex: 'operation',
      scopedSlots: {customRender: 'operation'},
    },
  ];

  export default {
    components: {
      ARow,
      TDictSelectTag,
    },
    props: {
      visible: {
        type: Boolean,
        required: true,
      },
      loading: {
        type: Boolean,
        default: () => false,
      },
      model: {
        type: Object,
        default: () => null,
      },
    },
    data() {
      return {
        title: '',
        labelCol: {
          xs: {
            span: 24,
          },
          sm: {
            span: 3,
          },
        },
        wrapperCol: {
          xs: {
            span: 24,
          },
          sm: {
            span: 20,
          },
        },
        form: this.$form.createForm(this),
        data: [],
        columns,
        count:0
      };
    },
    created() {
      // 防止表单未注册
      fields.forEach((v) => this.form.getFieldDecorator(v));
      // 当 model 发生改变时，为表单设置值
      this.$watch('model', () => {
        if(this.model && this.model.columsData){
          this.data = JSON.parse(JSON.stringify(this.model.columsData))
          //添加id
          this.data.forEach((item,index) =>{
            this.data[index].id = index
          })
          this.count = this.data.length
        }else {
          this.count = 0
          this.data = []
        }
        this.model && this.form.setFieldsValue(pick(this.model, fields));
      });
    },
    methods: {
      add(e) {
        this.form.setFieldsValue({
          tableName: '',
          tableComment: ''
        })
      },
      edit(e) {
      },
      //输入框内容改变，给当前数据赋值
      handleChange(value, index, column) {
        this.$set(this.data[index],column,value)
      },
      //删除
      handleDel(index){
        this.data.splice(index,1)
      },
      handleAdd(){
        this.data.unshift({
          id:this.count,
        });
        this.count++
      },
      getOptionRules(col){
        if(['fieldComment','defaultValue','fieldLength'].indexOf(col) !== -1){
          return [{ required: true, message: '必填!' }]
        }else if(col==='fieldName'){
          return [
            { required: true, message: '必填!' },
            {
              validator: this.columnNameValidator,
              message: "字段名不能重复!",
              trigger: "blur"
            }]
        }
      },
      columnNameValidator(rule,val){
        let count = 0;
        this.data.forEach((item,index) => {
          if(item.fieldName === val){
            count++
          }
        })
        return count === 1 || val === ''
      }
    },
  };
</script>
